package net.tngou.tnfs.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.jsoup.nodes.Document;




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class Img4s {

	private static final Logger log= LoggerFactory.getLogger(Img4s.class);
	private static final String ImgExt="jpg,png,gif,jpeg";
	
	
	
	/**
	 * 通过查询关键词  查询相关普通
	 * 该图片是基于360图片搜索来做数据源
	 * @param q
	 * @return
	 */
	public List<String> getImgUrl(String q) {
		
		    List<String> list = new ArrayList<String>();
		    String url = "http://image.so.com/j";
			Map<String, String>  map = new HashMap<String, String>();
			map.put("q", q);
			Document doc =HttpUtil.get(url,map);
			if(doc==null) return null ;
			String json=doc.body().text();
			System.err.println(json);
			try {
				JSONObject object = JSON.parseObject(json);
				if(object==null) return null ;
				if(object.getIntValue("lastindex")>0)
				{
					JSONArray jsonarray = object.getJSONArray("list");
					jsonarray.forEach(e->{
						JSONObject ee=(JSONObject) e;
						String img = ee.getString("img");
						String ext = FilenameUtils.getExtension(img).toLowerCase(); //文件后缀
						if(ImgExt.indexOf(ext)>-1)
							list.add(img);});
				}else
				{
					log.info("无法找到关键词-{}-匹配的图片",q);
					return null ;
				}
			} catch (Exception e) {
				// TODO: handle exception
				return null ;
			}
			
			
			//list.forEach(System.out::println);

		return list ;
		
	}
	
	
	
	
	
	public static void main(String[] args) {
		
	
		List<String> list = new ArrayList<String>();
		String url = "http://image.so.com/j";
	
			Map<String, String>  map = new HashMap<String, String>();
			map.put("q", "色情");
			Document doc =HttpUtil.get(url,map);
			String json=doc.body().text();
			JSONObject object = JSON.parseObject(json);
			if(object.getIntValue("lastindex")>0)
			{
				JSONArray jsonarray = object.getJSONArray("list");
				jsonarray.forEach(e->{
					JSONObject ee=(JSONObject) e;
					String img = ee.getString("img");
					String ext = FilenameUtils.getExtension(img).toLowerCase(); //文件后缀
					if(ImgExt.indexOf(ext)>-1)
					list.add(img);});
			}
			
			list.forEach(System.out::println);
		
			//Consumer<? super Object> doSomething = e->Imgs.doSomething((JSONObject) e);
			//jsonarray.forEach(System.out::println);
			//jsonarray.forEach(doSomething);
			
//			jsonarray.forEach(e->{
//				JSONObject ee=(JSONObject) e;
//				System.out.println(ee.getString("img"));});
			
			
		
		
	}
	
	
	
	
	
	 public static void doSomething(JSONObject e) {
	        System.out.println(e.getString("img"));
	         
	    }
}
